#include <cstdio>
#include <string>
#include <unistd.h>
#include <pthread.h>

struct data
{
    std::string name;
    pthread_mutex_t *lockp;
};

int ticket=1000;
// pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

void* route(void*args)
{
    data*d=static_cast<data*>(args);
    while(true)
    {
        pthread_mutex_lock(d->lockp);
        if(ticket>0)
        {
            usleep(10000);
            printf("%s 抢到票号：%d\n",d->name.c_str(),ticket--);
            pthread_mutex_unlock(d->lockp);
        }
        else
        {
            pthread_mutex_unlock(d->lockp);
            break;
        }
    }
    return (void*)0;
}


int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    pthread_t t1, t2, t3, t4;
    data d1 = {"thread-1", &lock};
    pthread_create(&t1, nullptr, route, (void*)&d1);

    data d2 = {"thread-2", &lock};
    pthread_create(&t2, nullptr, route, (void*)&d2);

    data d3 = {"thread-3", &lock};
    pthread_create(&t3, nullptr, route, (void*)&d3);

    data d4 = {"thread-4", &lock};
    pthread_create(&t4, nullptr, route, (void*)&d4);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    pthread_mutex_destroy(&lock);

    return 0;
}